package com.example.experiment3.service;

import com.example.experiment3.model.RegionStats;
import lombok.Data;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;


import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Data
@Component
public class CoronavirusDataService {
    /**
     * 初始化爬虫路径URL
     */
    public final static String COVID_DATASOURCE_URL="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";
    //打印日志信息
    private static final Logger log= LoggerFactory.getLogger(CoronavirusDataService.class);
    private static final SimpleDateFormat dataFormat=new SimpleDateFormat("HH:mm:ss");

    //所有的model类的对象组织为一个集合
    private List<RegionStats> allRegionsStats=new ArrayList<>();

    @Autowired
    private RestTemplate restTemplate;
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    /**
     * 爬取数据
     */
    @Scheduled(cron = "0 0 1 * * *")//每天凌晨1点执行定时任务，更新统计数据
    @PostConstruct
    public void fetchCoronavirusData(){
        //爬取csv文,指定请求标头
        URI uri= UriComponentsBuilder.fromUriString(COVID_DATASOURCE_URL).build(42);
        //实例化一个RequestEntity对象，通过RestTemplate的exchange方法获取csv文件，封装到body中
        RequestEntity<Void> requestEntity=RequestEntity.get(uri)
                .header("User-Agent","Mozilla/5.0")
                .build();
        ResponseEntity<Resource> exchange=restTemplate.exchange(requestEntity,Resource.class);
        Resource body=exchange.getBody();
        //分析 Excel CSV 文件（标题自动检测）-CSVReccord映射头并获取相应的值
        try {
            Reader in = new InputStreamReader(body.getInputStream());
            Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
            for (CSVRecord record : records) {
                this.allRegionsStats.add(new RegionStats()
                        .setState(record.get("Province/State"))
                        .setCountry(record.get("Country/Region"))
                        .setLatestTotalCases(Integer.valueOf(record.get(record.size() - 1)))
                        .setDiffFromPrevDay(Integer.valueOf(record.get(record.size() - 1))
                                - Integer.valueOf(record.get(record.size() - 2))));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        //打印日志信息
        log.info("Updata CoronavirusData in {}",dataFormat.format(new Date()));
    }


    @Component
    public class InitCoronavirusData implements InitializingBean{

        @Autowired
        private CoronavirusDataService coronavirusDataService;

        private List<RegionStats> allRegionsStats=new ArrayList<>();
        @Override
        public void afterPropertiesSet() throws Exception {
            log.info("项目启动时会执行，获取一次统计数据！");
            coronavirusDataService.getAllRegionsStats();
        }
    }
}
